<template>
  <div class="service-audit">
    <h1 class="page-title">服务审核</h1>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-header">
        <i class="filter-icon">⚙</i>
        <span>筛选</span>
      </div>
      <div class="filter-content">
        <el-input v-model="filterForm.doctorName" placeholder="输入医生姓名或账号" class="filter-input" />
        <el-select v-model="filterForm.department" placeholder="请选择科室" class="filter-select">
          <el-option label="心内科" value="心内科" />
          <el-option label="神经外科" value="神经外科" />
          <el-option label="儿科" value="儿科" />
          <el-option label="消化科" value="消化科" />
          <el-option label="内分泌科" value="内分泌科" />
        </el-select>
        <el-select v-model="filterForm.title" placeholder="请选择职称" class="filter-select">
          <el-option label="主任医师" value="主任医师" />
          <el-option label="副主任医师" value="副主任医师" />
          <el-option label="主治医师" value="主治医师" />
          <el-option label="住院医师" value="住院医师" />
          <el-option label="药剂师" value="药剂师" />
        </el-select>
        <el-button type="primary" @click="handleFilter" :loading="page.loading">筛选</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 医生列表 -->
    <div class="doctor-list-section">
      <div class="list-header">
        <i class="list-icon">📋</i>
        <span>医生列表</span>
        <span class="total-count">(共 {{ page.total }} 条数据)</span>
      </div>

      <el-table :data="doctorList" style="width: 100%" @selection-change="handleSelectionChange"
        v-loading="page.loading" element-loading-text="加载中...">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="hospital" label="医院" />
        <el-table-column prop="department" label="科室" />
        <el-table-column prop="title" label="职称" />
        <el-table-column prop="registrationTime" label="加入时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.registrationTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.auditStatus === '已通过' ? 'success' : 'warning'" size="small">
              {{ scope.row.auditStatus }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="serviceAudit" label="服务审核" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.serviceAudit === '待审核' ? 'warning' : 'info'" size="small">
              {{ scope.row.serviceAudit }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="goToDetailPage(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="openServiceAuditDialog(scope.row)">审核</el-button>
            <el-button size="small" type="danger" @click="">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页和批量操作 -->
      <div class="table-footer">
        <div class="batch-actions">
          <el-checkbox v-model="page.selectAll" @change="handleSelectAll">全选</el-checkbox>
          <span class="data-info">共{{ page.totalPages }}页/{{ page.total }}条数据</span>
        </div>
        <el-pagination v-model:current-page="page.currentPage" :page-size="page.pageSize" :total="page.total"
          :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange" @size-change="handleSizeChange" />
      </div>
    </div>

    <!-- 服务审核弹框 -->
    <el-dialog v-model="serviceAuditDialog.visible" title="服务审核" width="600px" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div class="service-audit-content">
        <div v-for="(step, index) in serviceAuditDialog.steps" :key="index" class="audit-step">
          <div class="step-header">
            <h4 class="service-name">{{ step.serviceName }}</h4>
          </div>
          <div class="step-content">
            <div class="audit-section">
              <label class="audit-label">审核：</label>
              <el-radio-group v-model="step.auditStatus" class="audit-options">
                <el-radio label="审核通过">审核通过</el-radio>
                <el-radio label="审核不通过">审核不通过</el-radio>
              </el-radio-group>
            </div>
            <div class="remarks-section">
              <label class="remarks-label">备注：</label>
              <el-input v-model="step.remarks" type="textarea" :rows="3" placeholder="请输入" class="remarks-input" />
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeServiceAuditDialog">取消</el-button>
          <el-button type="primary" @click="submitServiceAudit" :loading="serviceAuditDialog.submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { apiClient } from '@/api/doctor'


const router = useRouter()

// 筛选表单
const filterForm = reactive({
  doctorName: '',
  department: '',
  title: ''
})

// 分页数据
const page = reactive({
  currentPage: 1,
  pageSize: 5,
  total: 0,
  totalPages: 0,
  loading: false,
  selectAll: false
})

// 医生列表数据
const doctorList = ref([])
const selectedDoctors = ref([])

// 服务审核弹框数据
const serviceAuditDialog = reactive({
  visible: false,
  submitting: false,
  doctorId: 0,
  workflowId: 0,
  steps: [] as any[]
})

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    page.loading = true

    const queryParams: any = {
      pageIndex: page.currentPage,
      pageSize: page.pageSize,
      name: '',
      department: '',
      title: ''
    }

    // 添加筛选条件
    if (filterForm.doctorName) {
      queryParams.name = filterForm.doctorName
    }
    if (filterForm.department) {
      queryParams.department = filterForm.department
    }
    if (filterForm.title) {
      queryParams.title = filterForm.title
    }

    const result = await apiClient.get('/api/DoctorGetDoctorList', {
      params: queryParams
    })
    console.log(result);

    if (result.data.code === 100) { // Success
      // 确保 result.data.data 是数组
      doctorList.value = result.data.data.data
      page.total = result.data.data.totalCount
      page.totalPages = result.data.data.totalPages
      //ElMessage.success('获取医生列表成功')
    } else {
      ElMessage.error(result.data.message || '获取医生列表失败')
    }
  } catch (error: any) {
    console.error('获取医生列表失败:', error)
    ElMessage.error(error.message || '网络错误，请稍后重试')
  } finally {
    page.loading = false
  }
}

// 打开服务审核弹框
const openServiceAuditDialog = async (doctor: any) => {
  try {
    serviceAuditDialog.doctorId = doctor.id
    serviceAuditDialog.visible = true

    // 获取服务类型列表
    const serviceTypesResult = await apiClient.get('/api/WorkflowGetServiceTypes')
    // const serviceTypesResult = await workflowAPI.getServiceTypes()
    if (serviceTypesResult.data.code === 100) {
      // 初始化审核步骤
      serviceAuditDialog.steps = serviceTypesResult.data.data.map((serviceType: any) => ({
        serviceName: serviceType.name,
        auditStatus: '',
        remarks: '',
        serviceTypeId: serviceType.id
      }))
    } else {
      ElMessage.error('获取服务类型失败')
    }
  } catch (error: any) {
    console.error('打开服务审核弹框失败:', error)
    ElMessage.error('打开服务审核弹框失败')
  }
}

// 关闭服务审核弹框
const closeServiceAuditDialog = () => {
  serviceAuditDialog.visible = false
  serviceAuditDialog.steps = []
  serviceAuditDialog.doctorId = 0
  serviceAuditDialog.workflowId = 0
}

// 提交服务审核
const submitServiceAudit = async () => {
  try {
    // 验证是否所有步骤都已审核
    const unAuditedSteps = serviceAuditDialog.steps.filter(step => !step.auditStatus)
    if (unAuditedSteps.length > 0) {
      ElMessage.warning('请完成所有服务类型的审核')
      return
    }

    serviceAuditDialog.submitting = true

    // 获取选中的服务类型ID
    const selectedServiceTypeIds = serviceAuditDialog.steps
      .filter(step => step.auditStatus === '审核通过')
      .map(step => step.serviceTypeId)

    if (selectedServiceTypeIds.length === 0) {
      ElMessage.warning('请至少选择一个服务类型')
      return
    }

    // 创建工作流
    const createWorkflowResult = await apiClient.post('/api/WorkflowCreateWorkflow', {
      doctorId: serviceAuditDialog.doctorId,
      serviceTypeIds: selectedServiceTypeIds
    })

    if (createWorkflowResult.data.code === 100) {
      serviceAuditDialog.workflowId = createWorkflowResult.data.data.id

      // 更新每个步骤的审核状态
      for (const step of serviceAuditDialog.steps) {
        if (step.auditStatus) {
          // 找到对应的工作流步骤
          const workflowStep = createWorkflowResult.data.data.steps.find(
            (s: any) => s.serviceName === step.serviceName
          )

          if (workflowStep) {
            await apiClient.put('/api/WorkflowUpdateWorkflowStep', {
              stepId: workflowStep.id,
              auditStatus: step.auditStatus,
              remarks: step.remarks,
              auditor: '审核员' // 这里可以从登录用户信息获取
            })/* .updateWorkflowStep({
              stepId: workflowStep.id,
              auditStatus: step.auditStatus,
              remarks: step.remarks,
              auditor: '审核员' // 这里可以从登录用户信息获取
            }) */
          }
        }
      }

      ElMessage.success('服务审核提交成功')
      closeServiceAuditDialog()
      fetchDoctorList() // 刷新医生列表
    } else {
      ElMessage.error(createWorkflowResult.data.message || '服务审核提交失败')
    }
  } catch (error: any) {
    console.error('提交服务审核失败:', error)
    ElMessage.error('提交服务审核失败')
  } finally {
    serviceAuditDialog.submitting = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 事件处理
const handleFilter = () => {
  page.currentPage = 1 // 重置到第一页
  fetchDoctorList()
}

const handleReset = () => {
  filterForm.doctorName = ''
  filterForm.department = ''
  filterForm.title = ''
  page.currentPage = 1
  fetchDoctorList()
}

const handleSelectionChange = (selection: any) => {
  selectedDoctors.value = selection
  page.selectAll = selection.length === doctorList.value.length && doctorList.value.length > 0
}

const handleSelectAll = (val: boolean) => {
  if (val) {
    selectedDoctors.value = [...doctorList.value]
  } else {
    selectedDoctors.value = []
  }
}

/* const handleBatchDelete = async () => {
  if (selectedDoctors.value.length === 0) {
    ElMessage.warning('请先选择要删除的医生')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedDoctors.value.length} 个医生吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 调用批量删除 API
    const doctorIds = selectedDoctors.value.map(doctor => doctor.id)
    // const result = await doctorAPI.batchDeleteDoctors(doctorIds)
    // if (result.code === 100) {
    //   ElMessage.success(`批量删除 ${selectedDoctors.value.length} 个医生成功`)
    //   fetchDoctorList() // 重新加载数据
    // } else {
    //   ElMessage.error(result.message || '批量删除失败')
    // }
    ElMessage.success(`批量删除 ${selectedDoctors.value.length} 个医生成功`)
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '批量删除失败')
    } else {
      ElMessage.info('已取消批量删除')
    }
  }
}
 */
const handlePageChange = (pages: number) => {
  page.currentPage = pages
  fetchDoctorList()
}

const handleSizeChange = (size: number) => {
  page.pageSize = size
  page.currentPage = 1
  fetchDoctorList()
}

// 跳转到医生详情页面
const goToDetailPage = (doctor: any) => {
  // 使用 Vue Router 跳转到医生详情页面
  router.push({
    name: 'doctor-detail',
    query: { id: doctor.id }
  })
  ElMessage.success(`正在打开医生 ${doctor.name} 的详情页面`)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchDoctorList()
})
</script>

<style scoped>
.service-audit {
  padding: 20px;
  background-color: #f5f5f5;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.filter-section,
.doctor-list-section {
  background: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-header,
.list-header {
  background: #f0f0f0;
  padding: 12px 16px;
  border-radius: 8px 8px 0 0;
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #666;
}

.total-count {
  margin-left: auto;
  font-size: 14px;
  color: #999;
}

.filter-content {
  padding: 20px;
  display: flex;
  gap: 16px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-input {
  width: 200px;
}

.filter-select {
  width: 150px;
}

.doctor-list-section {
  padding-bottom: 0;
}

.table-footer {
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #eee;
}

.batch-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.data-info {
  color: #666;
  font-size: 14px;
}

/* 服务审核弹框样式 */
.service-audit-content {
  max-height: 400px;
  overflow-y: auto;
}

.audit-step {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fafafa;
}

.step-header {
  margin-bottom: 12px;
}

.service-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.step-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.audit-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.audit-label {
  font-weight: 500;
  color: #555;
  min-width: 60px;
}

.audit-options {
  display: flex;
  gap: 16px;
}

.remarks-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.remarks-label {
  font-weight: 500;
  color: #555;
}

.remarks-input {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
}

:deep(.el-loading-mask) {
  border-radius: 0;
}

.doctor-detail {
  padding: 20px;
}

.detail-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.detail-section:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.detail-section h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.detail-grid {
  display: grid;
  grid-template-columns: 120px 1fr;
  gap: 10px 20px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  color: #555;
  margin-right: 10px;
}

.detail-item span {
  font-size: 15px;
  color: #444;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}
</style>